import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "@/layout";
import instance from "@/api/request";
import Cookies from "js-cookie";

Vue.use(VueRouter);

let routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/view/Login/index.vue"),
  },
];

const router = new VueRouter({
  routes,
});

function loadView(view) {
  return () => import(`@/view${view}.vue`);
}

function getOther(list) {
  return list.map((item) => {
    const newItem = { ...item, ...item.thisData };
    if (newItem.isHideen === 0) {
      newItem.isHiddenName = "隐藏";
    } else if (newItem.isHideen === 1) {
      newItem.isHiddenName = "显示";
    }
    newItem.path = newItem.url;
    newItem.component = loadView(newItem.fileUrl);

    if (item.childList && item.childList.length > 0) {
      newItem.childList = getOther(item.childList);
    }

    return newItem;
  });
}

function flattenMenuArray(arr) {
  let result = [];

  function recurse(items) {
    items.forEach((item) => {
      result.push(item);
      if (item.childList && item.childList.length > 0) {
        recurse(item.childList);
      }
    });
  }

  recurse(arr);
  return result;
}

router.beforeEach((to, from, next) => {
  let storedRoutes = localStorage.getItem("menuList") || "[]";
  storedRoutes = JSON.parse(storedRoutes);
  let roleId = Cookies.get('roleId')
  if (!roleId) {
    storedRoutes = []
  }
  if (
    (storedRoutes.length == 0 && to.path == "/") ||
    (storedRoutes.length == 0 && to.path != "/login")
  ) {
    next("/login");
  } else if (storedRoutes.length > 0 && to.path == "/") {
    next(`${storedRoutes[0].url}`);
  } else if (router.getRoutes().length < 2 && to.path !== from.path) {
    try {
      const roleId = localStorage.getItem("roleId") || "100";
      // const roleId = '100'
      const url = `/government-platform-center/menu/queryByRoleId?roleId=${roleId}`;
      instance.get(url, {}).then((res2) => {
        if (res2.data.code == 0) {
          const tableData = res2.data.data;
          // tableData.push({
          //   thisData: {
          //     createTime: '2024-11-18 15:05:11',
          //     updateTime: '2024-11-19 23:38:03',
          //     deleted: 0,
          //     menuId: 1122,
          //     menuName: '角色管理',
          //     menuType: 'C',
          //     orderNum: 0,
          //     parentId: 0,
          //     remark: '',
          //     url: '/role',
          //     fileUrl: 'Role/index.vue',
          //     isHideen: 1,
          //   },
          //   id: 2199,
          //   parentId: 0,
          //   childList: [],
          // })
          const deal = getOther(tableData);
          const routerData = flattenMenuArray(deal);
          router.addRoute({
            path: "/",
            component: Layout,
            redirect: routerData[0].thisData.url,
            children: routerData,
          });
        }
      });
      next();
    } catch (error) {
      console.log(error);
    }
  } else {
    next();
  }
});
export default router;
